package com.duckygo.towerdefense.game;

import java.util.Arrays;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;

public class TextureManager {
	
	private static final int MAX_TEXTURES = 20;
	
	public static int[] textures = new int[MAX_TEXTURES];
	
	public static int lastTexture = Integer.MIN_VALUE;

	private static int[] lastTextureCrop;

	
	public static final void bindTexture(GL10 gl, int texture, int[] crop) {
		GL11 gl1 = (GL11)gl;
		
		if (texture != lastTexture) 
			gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[texture]);
		if (crop != null) {
			if (lastTextureCrop == null || !Arrays.equals(lastTextureCrop, crop)) {
			//	Log.w("TextureManager", "Texture crop [" + crop[0] + "," + crop[1] + "," + crop[2] + "," + crop[3] + "]");
			}
			gl1.glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, crop, 0);
		}
			
		lastTexture = texture;
		lastTextureCrop = crop;
	}
	
	public static final void loadTexture(GL10 gl, Context context, int resId, int id) {
		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
		loadTexture(gl, bitmap, id);
	}
	
	public static final void loadTexture(GL10 gl, Bitmap bitmap, int id) {
		gl.glGenTextures(1, textures , id);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[id]);
			
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
			
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
	}
	
}
